package com.abel.bigwater.dataserver.model

import com.abel.bigwater.data.BcdString
import io.netty.buffer.Unpooled
import org.junit.Assert.*
import org.junit.Test
import org.slf4j.LoggerFactory

class PacketUtilTest {
    @Test
    fun testCrc16() {
        // 0x02 05 00 03 FF 00 , crc16=7C 09
        val crc = PacketUtil.calcCrc16(byteArrayOf(0x02, 0x05, 0x00, 0x03, 0xff.toByte(), 0x00))
        println(String.format("0x%04x", crc))
    }

    @Test
    fun testEncrypt() {
        val plain = byteArrayOf(0x10, 1, 2, 3, 4, 5)
        val scrt = PacketUtil.kmingEncrpt(plain)

        lgr.info("secret: {}", BcdString.hexString(scrt, true))

        val pl2 = PacketUtil.kmingDecrypt(scrt)
        lgr.info("plain after decrypt: {}", BcdString.hexString(pl2, true))

        assertArrayEquals(plain, pl2)
    }

    @Test
    fun testShort() {
        val buf = Unpooled.buffer()
        buf.writeShort(1)
        assertEquals(1.toShort(), buf.readShort())

        buf.writeShort(0x11)
        lgr.info("short (be): ${BcdString.hexString(buf, withBlank = true)}")
        lgr.info("short (le): ${buf.duplicate().readUnsignedShortLE()}")
        assertEquals(0x11, buf.duplicate().readUnsignedShort())
    }

    companion object {
        private val lgr = LoggerFactory.getLogger(PacketUtilTest::class.java)
    }
}